package com.yds.bluetooth

import android.annotation.SuppressLint
import android.bluetooth.BluetoothGatt
import android.bluetooth.BluetoothGattCharacteristic
import android.bluetooth.BluetoothGattDescriptor
import android.util.Log
import java.util.UUID

class BLENotificationHandler {
    companion object {
        private const val TAG = "YDSimon"
    }

    private var mGatt: BluetoothGatt? = null

    fun enableAllNotifications(gatt: BluetoothGatt?) {
        mGatt = gatt
        val services = mGatt!!.services
        for (service in services) {
            val characteristics = service.characteristics
            for (characteristic in characteristics) {
                if (characteristic.properties and BluetoothGattCharacteristic.PROPERTY_NOTIFY != 0) {
                    enableNotification(characteristic)
                }
            }
        }
    }

    @SuppressLint("MissingPermission")
    private fun enableNotification(characteristic: BluetoothGattCharacteristic) {
        if (mGatt!!.setCharacteristicNotification(characteristic, true)) {
            val descriptor = characteristic.getDescriptor(UUID.fromString("00002902-0000-1000-8000-00805f9b34fb"))
            if (null != descriptor) {
                descriptor.value = BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE
                val b = mGatt!!.writeDescriptor(descriptor)
                Log.i(TAG, "enableAllNotifications: " + characteristic.uuid + "  " + b)
            }
        }
    }


}